package com;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author N_Xiang
 * @describe 注解解析器
 * @time 2022/2/24 10:19 下午
 */
public class SrStruct {
    /**
     * 字段注解中强转属性map
     * K:字段名
     * V:类型枚举
     */
    private static Map<String, StructEnum> fieldMap = new ConcurrentHashMap<>();
    /**
     * 字段FieldMap
     * K：字段名
     * V：Field
     */
    private static Map<String, Field> fieldTypeMap = new ConcurrentHashMap<>();
    /**
     * 长度属性的值，k：filed v：长度
     */
    private static Map<Field, Integer> lengthMap = new ConcurrentHashMap<>();
    /**
     * 统计所有有长度属性的字段  k：filed名字
     */
    private static Map<String, String> lengthMethodMap = new ConcurrentHashMap<>();

    /**
     * 将实体类中的注解字段分解
     *
     * @param cls 实体类Object
     * @return
     */
    private static SortedMap<Integer, Field> parsStruct(Object cls) {
        return parsStruct(cls.getClass());
    }

    /**
     * 将实体类中的注解字段分解
     *
     * @param cls 实体类Class
     * @return
     */
    private static SortedMap<Integer, Field> parsStruct(Class<?> cls) {

        if (!ObjectUtils.isEmpty(StructCache.ANN_FIELD_MAP.get(cls))) {
            fieldMap = StructCache.ANN_FIELD_MAP.get(cls);
            fieldTypeMap = StructCache.ANN_FIELD_TYPE_MAP.get(cls);
            lengthMap = StructCache.ANN_LENGTH_MAP.get(cls);
            lengthMethodMap = StructCache.ANN_LENGTH_METHOD_MAP.get(cls);
            return StructCache.ANN_LABEL_MAP.get(cls);
        }
        SortedMap<Integer, Field> lableMap = new TreeMap<>();
        Field[] fields = cls.getDeclaredFields();
        Arrays.stream(fields).forEach(f -> {
            if (f.isAnnotationPresent(Struct.class)) {
                Struct annotation = f.getAnnotation(Struct.class);
                int value = annotation.order();
                StructEnum value1 = annotation.value();
                String s = annotation.lengthMethod();
                int length = annotation.length();
                if (value1 != StructEnum.Null) {
                    fieldMap.put(f.getName(), value1);
                }
                lengthMap.put(f, length);
                lengthMethodMap.put(f.getName(), s);
                if (!ObjectUtils.isEmpty(lableMap.get(value))) {
                    throw new RuntimeException("在" + cls.getName() + " 中 " + f.getName() + " 字段@Struct的order属性出现重复！");
                }
                lableMap.put(value, f);
                fieldTypeMap.put(f.getName(), f);
            }
        });
        StructCache.ANN_FIELD_MAP.put(cls, fieldMap);
        StructCache.ANN_FIELD_TYPE_MAP.put(cls, fieldTypeMap);
        StructCache.ANN_LENGTH_MAP.put(cls, lengthMap);
        StructCache.ANN_LENGTH_METHOD_MAP.put(cls, lengthMethodMap);
        StructCache.ANN_LABEL_MAP.put(cls, lableMap);
        return lableMap;
    }

    @Deprecated
    public static void translation(Object o, byte[] bytes) {
        translation(o, ByteBuffer.wrap(bytes));
    }

    @Deprecated
    public static void translation(Class<?> o, byte[] bytes) {
        try {
            translation(o.newInstance(), ByteBuffer.wrap(bytes), 0);
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Deprecated
    public static void translation(Object o, byte[] bytes, int offset) {
        translation(o, ByteBuffer.wrap(bytes), offset);
    }

    @Deprecated
    public static void translation(Object o, String bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(StringToHex.hexStr2Byte(bytes));
        translation(o, buffer);
    }

    public static void translation(Object o, ByteBuffer buffer) {
        translation(o, buffer, 0);
    }

    @Deprecated
    public static void translation(Object o, String bytes, int offset) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(StringToHex.hexStr2Byte(bytes));
        translation(o, byteBuffer, offset);
    }

    @Deprecated
    public static <T> T translation(Class<T> cls, String bytes) {
        ByteBuffer byteBuffer = ByteBuffer.wrap(StringToHex.hexStr2Byte(bytes));
        try {
            T tclass = cls.newInstance();
            translation(tclass, byteBuffer, 0);
            return tclass;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    public static <T> T translation(Class<T> cls, ByteBuffer buffer) {
        try {
            T tclass = cls.newInstance();
            translation(tclass, buffer, 0);
            return tclass;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T translation(Class<T> cls, ByteBuffer buffer, int offset) {
        try {
            T tclass = cls.newInstance();
            translation(tclass, buffer, offset);
            return tclass;
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 解构为JavaBean
     *
     * @param source 目标对象
     * @param buffer 字节流
     * @param offset 偏移量
     */
    public static void translation(Object source, ByteBuffer buffer, int offset) {
//        设置偏移量
        buffer.position(offset);
//        获取结构体注解
        SortedMap<Integer, Field> map = parsStruct(source);
        for (Map.Entry<Integer, Field> entry : map.entrySet()) {
//            获取字段
            Field v = entry.getValue();
//            获取字段Type
            Class<?> type = getType(v);
//            获取字段名
            String name = getName(v);
//            获取set方法名
            String setMethodName = fieldSetMethodName(name);
//            获取set方法
            Method setMethod = MethodBySet(source, setMethodName, type);

            try {
//                判断是否是子类，子类进入递归
                if (!ObjectUtils.isEmpty(getType(v).getSuperclass()) && !getType(v).equals(byte[].class) && !getType(v).equals(String.class) && getType(v).getSuperclass().equals(Object.class)) {
                    Object subclass = getType(v).newInstance();
                    translation(subclass, buffer, buffer.position());
                    setMethod.invoke(source, subclass);
                    continue;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

//            获取需要取字节的长度
            int len = getLength(source, name, type, v);

//            获取byte流中对应的数据
            Object deconstructedValue = typeToObject(type, buffer, len, fieldMap.get(name));

//            将解构的数据存储到目标Bean
            try {
                setMethod.invoke(source, deconstructedValue);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    public static void unTranslation(Object o, String bytes) {
        unTranslation(o, StringToHex.hexStr2Byte(bytes));
    }

    /**
     * 通过结构体构建成Byte数组
     *
     * @param source 源对象
     * @param bytes  byte数组
     */
    public static void unTranslation(Object source, byte[] bytes) {

    }


    /**
     * 获取字段type
     *
     * @param field 字段Field
     * @return
     */
    private static Class<?> getType(Field field) {
        return field.getType();
    }

    /**
     * 获取字段名
     *
     * @param field 字段Field
     * @return
     */
    private static String getName(Field field) {
        return field.getName();
    }


    /**
     * 将bytebuffer中的值取出
     *
     * @param type       源字段类型
     * @param buffer     源buffer数据
     * @param length     取得字段长度
     * @param structEnum 字段目标类型
     * @return
     */
    private static Object typeToObject(Class<?> type, ByteBuffer buffer, int length, StructEnum structEnum) {
        if (type.equals(String.class)) {
            if (length == 0) {
                length = 1;
            }
            byte[] bytes1 = new byte[length];
            buffer.get(bytes1);
            if (ObjectUtils.isEmpty(structEnum)) {
                return StringToHex.bytesToHexString(bytes1);
            } else if (structEnum == StructEnum.Byte) {
                return StringToHex.byteArraytoByteString(bytes1);
            } else {
                return StringToHex.bytesToHexString(bytes1);
            }
        }
        else if (type.equals(int.class) || type.equals(Integer.class) ) {
            return buffer.getInt();
        } else if (type.equals(short.class) || type.equals(Short.class) ) {
            return buffer.getShort();
        } else if (type.equals(Byte.class)) {
            return buffer.get();
        } else if (type.equals(byte.class) ) {
            return buffer.get();
        } else if (type.equals(byte[].class)) {
            byte[] bytes = new byte[length];
            buffer.get(bytes);
            return bytes;
        }
        else {
            throw new RuntimeException(type.getName() + "是不支持的属性");
        }
    }

    /**
     * 获取set方法
     *
     * @param source        源对象
     * @param setMethodName set字段名
     * @param type          源字段类型
     * @return
     */
    private static Method MethodBySet(Object source, String setMethodName, Class<?> type) {
        Method method = StructCache.ANN_METHOD_MAP.get(source + setMethodName);
        if (ObjectUtils.isEmpty(method)) {
            try {
                method = source.getClass().getMethod(setMethodName, type);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
            StructCache.ANN_METHOD_MAP.put(source + setMethodName, method);
        }
        return method;
    }

    /**
     * 获取get方法
     *
     * @param source        源对象
     * @param getMethodName get字段名
     * @param type          源字段类型
     * @return
     */
    private static Method MethodByGet(Object source, String getMethodName, Class<?> type) {
        Method method = StructCache.ANN_METHOD_MAP.get(source + getMethodName);
        if (ObjectUtils.isEmpty(method)) {
            try {
                method = source.getClass().getMethod(getMethodName);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
            StructCache.ANN_METHOD_MAP.put(source + getMethodName, method);
        }

        return method;
    }

    /**
     * 获取get方法名
     *
     * @param name 源字段名
     * @return
     */
    private static String fieldGetMethodName(String name) {
        String lengthMethodMapLetter = name.substring(0, 1).toUpperCase().concat(name.substring(1));
        return "get" + lengthMethodMapLetter;
    }

    /**
     * 获取set方法名
     *
     * @param name 源字段名
     * @return
     */
    private static String fieldSetMethodName(String name) {
        String lengthMethodMapLetter = name.substring(0, 1).toUpperCase().concat(name.substring(1));
        return "set" + lengthMethodMapLetter;
    }

    /**
     * 获取字段值
     *
     * @param type1     字段类型
     * @param getMethod get方法
     * @param source    源对象
     */
    private static int getValue(Type type1, Method getMethod, Object source) {
        try {
            if (type1.equals(int.class) || type1.equals(Integer.class)
                    || type1.equals(short.class) || type1.equals(Short.class)
                    || type1.equals(double.class) || type1.equals(Double.class)
                    || type1.equals(long.class) || type1.equals(Long.class)) {
                Number invoke = (Number) getMethod.invoke(source);
                return invoke.intValue();
            } else if (type1.equals(byte.class) || type1.equals(Byte.class)) {
                return (byte) getMethod.invoke(source) & 0xFF;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取长度
     *
     * @param source 源对象
     * @param name   目标字段名
     * @param type   目标字段类型
     * @param v      字段Field
     */
    private static int getLength(Object source, String name, Class<?> type, Field v) {
//            判断当前字段 @注解中是否有 lengthMethod 属性的字段名
        String lengthMethodName = lengthMethodMap.get(name);
        if (!StringUtils.isEmpty(lengthMethodName)) {
            //获取目标字段的get方法名
            String getLengthMethodMapName = fieldGetMethodName(lengthMethodName);

            //获取目标字段的get方法
            Method getMethod = MethodByGet(source, getLengthMethodMapName, type);

            //从内存中获取到目标字段对应到Field属性
            Field field = fieldTypeMap.get(lengthMethodName);
            if (ObjectUtils.isEmpty(field)) {
                throw new RuntimeException("没有在当前对象中找到属性" + lengthMethodName);
            }
            //获取目标字段Type
            Class<?> targetType = field.getType();
            //取出长度值，并赋值给当前字段
            return getValue(targetType, getMethod, source);
        } else {
//            没有 lengthMethod 属性就获取定义的length属性或者默认值
            return lengthMap.get(v);
        }
    }
}